﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using ServiceStack.Text;
using Framework.Library.Core.Config;
using Framework.Library.Core.Provider.Log;

namespace Framework.Library.Core.Provider.Payment
{
    public class KeyAccess
    {
        public string access_token { get; set; }
        public string code { get; set; }
        public long expires { get; set; }
        public string User { get; set; }
        public long UserId { get; set; }
    }
    public class Vcoin
    {
        public int _code { get; set; }
        public double _data { get; set; }
        public string _message { get; set; }
        public int _extensiveInformatio { get; set; }
    }

    public class ResponCodeEbankBuyItem
    {
        public int _code { get; set; }
        public ResponCodeEbankDataBuyItem _data { get; set; }
        public string _message { get; set; }
    }

    public class ResponCodeEbankDataBuyItem
    {
        public int ResponseCode { get; set; }
        public string Sign { get; set; }
        public int TotalVcoinGame { get; set; }
        public int TotalVcoinPayment { get; set; }
    }

    public class ResponCodeEbankPay
    {
        public int _code { get; set; }
        public ResponCodeEbankDataPay _data { get; set; }
        public string _message { get; set; }
    }

    public class ResponCodeEbankDataPay
    {
        public int Gift { get; set; }
        public int MoneyBetting { get; set; }
        public int ResponseCode { get; set; }
        public string Sign { get; set; }
        public int TotalVcoin { get; set; }
        public int TransID { get; set; }
        public int Vcoin { get; set; }
    }

    public class VcoinService
    {
        public string StringAuthentication(string urlCallback)
        {
            if (!string.IsNullOrEmpty(urlCallback))
                urlCallback = "&redirect_uri=" + urlCallback;
            return "http://graph.go.vn/oauth/authorize?client_id=" + Configurations.ClientID + urlCallback;
        }
        public KeyAccess GetAccess_token(string code)
        {
            try
            {
                string urlString = "http://graph.go.vn/oauth/access_token?client_id=" + Configurations.ClientID + "&code=" + code + "&client_secret=" +
                        Configurations.ClientSecret + "&redirect_uri=" + Configurations.ROOTPATH;
                string st = HttpGet(urlString);
                if (string.IsNullOrEmpty(st))
                    return null;
                KeyAccess info = JsonSerializer.DeserializeFromString<KeyAccess>(st);
                if (info != null)
                    return info;
                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }
        public double GetCurrentVcoin(string access_token)
        {
            try
            {
                var urlString = "http://graph.go.vn/ebank/payment/?access_token=" + access_token + Configurations.IsEbankTest;
                string st = HttpGet(urlString);
                Logger.Info("Get current payment vcoin", st);
                if (string.IsNullOrEmpty(st)) return 0;
                return JsonSerializer.DeserializeFromString<Vcoin>(st)._data;
            }
            catch
            {
                //Provider.TokenKeyBussiness.TokenKeyError(access_token);
                //Logger.Info("error Get current vcoin");
                return 0;
            }
        }
        public int BuyItem(string access_token, int vcoin)
        {
            try
            {
                string urlString;
                urlString = "http://graph.go.vn/ebank/buyitems?access_token=" + access_token;
                string strPost = "md5key=" + Configurations.md5key + "&transId=" + Configurations.TransID + "&itemcode=100&itemprice=" + vcoin + "&accountIP=127.0.0.1&makercode=" +
                         Configurations.makercode + "&serviceAppId=" + Configurations.serviceAppId + "&serviceKey=" + Configurations.serviceKey +
                          "&transdate=20120703113006&paymentType=paymentvcoin" + Configurations.IsEbankTest;

                string result = HttpPost(urlString, strPost);
                var inPutResult = JsonSerializer.DeserializeFromString<ResponCodeEbankBuyItem>(result);
                Logger.Info("Build item", result);
                if (inPutResult._code < 0)
                    return -200;
                else
                    return inPutResult._data.TotalVcoinPayment;
            }
            catch
            {
                return -500;
            }
        }
        /// <summary>
        /// Post dât 
        /// </summary>
        /// <param name="urlString"></param>
        /// <param name="strPost">name1=value1&name2=value2</param>
        /// <returns></returns>
        public string HttpPost(string urlString, string strPost)
        {

            string result = "";

            StreamWriter myWriter = null;

            HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(urlString);
            objRequest.Method = "POST";
            objRequest.ContentLength = strPost.Length;
            objRequest.ContentType = "application/x-www-form-urlencoded";

            try
            {
                myWriter = new StreamWriter(objRequest.GetRequestStream());
                myWriter.Write(strPost);
            }
            catch (Exception e)
            {
                return e.Message;
            }
            finally
            {
                myWriter.Close();
            }

            HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
            using (StreamReader sr =
                new StreamReader(objResponse.GetResponseStream()))
            {
                result = sr.ReadToEnd();

                // Close and clean up the StreamReader
                sr.Close();
            }

            return result;
        }

        public string HttpGet(string urlString)
        {
            string result = "";
            var u = new UriBuilder(urlString);
            WebRequest request = WebRequest.Create(u.Uri);
            request.Method = WebRequestMethods.Http.Get;
            WebResponse response = request.GetResponse();

            if (response != null)
            {
                Stream responseStream = response.GetResponseStream();
                if (responseStream != null)
                    using (var reader = new StreamReader(responseStream))
                    {
                        var text = reader.ReadToEnd();
                        result = text;
                    }
            }
            return result;
        }
    }
}
